package com.example.shengyin.controller;

import com.alibaba.fastjson2.JSON;
import com.example.shengyin.entity.Page;
import com.example.shengyin.entity.Seeker;
import com.example.shengyin.service.SeekerService;
import com.example.shengyin.util.Result;
import com.example.shengyin.util.StrUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.*;


/**
 * 应聘者Controller
 *
 * @author ruoyi
 * @date 2023-08-03
 */
@RestController
@RequestMapping("/seeker")
public class SeekerController {

    @Value("${upload-path}")
    private String path;

    @Autowired
    private SeekerService service;

    /**
     * 查询应聘者列表
     */
    @ApiOperation("查询所有应聘者姓名、手机号、简历地址等信息")
    @GetMapping("/list")
    public Result list(@ApiParam(name = "page",  value = "页数" )  int page,
                       @ApiParam(name = "limit",value = "页条数")  int limit,
                        @ApiParam(name = "jname", value = "应聘者") @RequestParam(required = false) String jname,
                       @ApiParam(name = "phone", value = "手机号") @RequestParam(required = false) String phone) {
//        Page page1 = new Page(page,limit);
//        System.out.println("page:" + page);
        Page page1 = service.selectSeekerList(page, limit, jname, phone);
        int count = service.countTotall(jname, phone);
        if (page1.getCount() == 0 || page1.getData() == null)
            return Result.success(page, "没有数据");
//        page.setData(list);
//        page.setCount(count);
        System.out.println(JSON.toJSONString(Result.success(page)));
        return Result.success(page1);
    }

    @ApiOperation("查找某个应聘者所有信息")
    @GetMapping(value = "/select/{id}")
    public Result select(@PathVariable(value = "id") Long id) {
        Seeker seeker = service.selectSeekerById(id);
        if (seeker == null)
            return Result.error("没有找到数据");
        return Result.success(seeker);
    }


    @ApiOperation("更新应聘者姓名、手机号等信息")
    @PostMapping("/edit")
    public Result edit(Seeker seeker) {
        Timestamp d = new Timestamp(System.currentTimeMillis());
        seeker.setPosttime(d);
        int insert = service.updateSeeker(seeker);
        if (insert == 0)
            return Result.error("修改失败");
        return Result.success("修改成功");
    }


    @ApiOperation("根据编号一次删除多个应聘者信息")
    @GetMapping("/deleteById/{ids}")
    public Result deleteById(@PathVariable(value = "ids") Long ids) {

        int delete = service.deleteSeekerById(ids);
        if (delete == 0)
            return Result.error("删除失败");
        return Result.success("删除成功");
    }

    @ApiOperation("根据编号一次删除多个应聘者信息")
    @GetMapping("/deleteByIds/{ids}")
    public Result deleteByIds(@PathVariable(value = "ids") Long[] ids) {

        int delete = service.deleteSeekerByIds(ids);
        if (delete == 0)
            return Result.error("删除失败");
        return Result.success("删除成功");
    }

    @ApiOperation("添加应聘者")
    @PostMapping("/add")
    public Result insert(@Valid Seeker seeker, BindingResult bindingResult) {
        Timestamp d = new Timestamp(System.currentTimeMillis());
        seeker.setPosttime(d);
        int insert = service.insertSeeker(seeker);
        if (insert == 0)
            return Result.error("添加失败");
        return Result.success("添加成功");
    }

    /**
     * 上传简历
     * doresume
     */

    @ApiOperation("简历上传,这是前端接口")
    @PostMapping("/doresume")
    public Result UploadResume(@RequestParam(value = "file") MultipartFile file) {
        //处理文件
        Map<String, Object> m = new HashMap<>();
        System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        System.out.println("????>>>??????" + file);
        if (file != null && !file.isEmpty()) {
            File f = new File(path);
            if (!f.exists())
                f.mkdirs();
            //原来的文件名
            String filename = file.getOriginalFilename();
            String houzhui = filename.substring(filename.lastIndexOf('.'));
            String newName = UUID.randomUUID() + houzhui;
            System.out.println("newName=" + newName);

            try {
                file.transferTo(new File(f, newName));
                m.put("code", 0);

                return Result.success("img/" + newName, "上传成功");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        m.put("code", 415);
        m.put("msg", "图片没有选择");
        return Result.error(415, "上传失败");
    }

    /**
     * 存储岗位投递人员的信息，含简历上传
     */

    @ApiOperation("存储岗位投递人员的信息，表单提交,这是前端接口")
    @PostMapping("/upload")
    public Result resumeUpload(@Validated Seeker seeker, String fileUrl) {
        Timestamp d = new Timestamp(System.currentTimeMillis());
        seeker.setPosttime(d);
        System.out.println(fileUrl);

        seeker.setResumeUrl(fileUrl);

        System.out.println(seeker.toString());
        int insert = service.insertSeeker(seeker);
        if (insert == 1) {
            return Result.success("添加成功");
        }
        return Result.error("添加失败");
    }


//    @RequestMapping("/downloadFile")
//    public void downloadFile1(@RequestParam("id") Long id, HttpServletResponse response) throws Exception {
//
//        Seeker seeker = service.selectSeekerById(id); //找到seeker 信息
//        // Professor p = this.professorService.get(id);//找到项目信息
//        System.out.println("seeker=" + seeker);
//        String realPath = "http://localhost:8020" + contexPath + "/" + seeker.getResumeUrl();
//
//        Map<String, Object> map = new HashMap<>();
//        map.put("seeker", seeker);
//
//        File file = new File(realPath);
//        System.out.println("file=" + file);
//        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(seeker.getJname(), "UTF-8"));
//        FileInputStream fin = new FileInputStream(file);
//        byte[] b = new byte[fin.available()];
//        fin.read(b);
//        fin.close();
//        ServletOutputStream out = response.getOutputStream();
//        out.write(b);
//        out.flush();
//        // file.delete();//下载后删除文件
//    }

    @ApiOperation("下载简历")
    @GetMapping(value = "/download/{id}")
    public void downloadFile(@PathVariable(value = "id") Long id,
                             HttpServletResponse response) throws UnsupportedEncodingException {

        Seeker seeker = service.selectSeekerById(id); //找到seeker 信息
        // Professor p = this.professorService.get(id);//找到项目信息
        System.out.println("seeker=" + seeker);
        // String realPath = /*"http://localhost:8020" + contexPath + "/" + */path + "/" + seeker.getResumeUrl();
        String resumeUrl = seeker.getResumeUrl();
        String substring = resumeUrl.substring(3, resumeUrl.length());
        // String realPath =path + "/" + seeker.getResumeUrl();
        String realPath =path + substring;

        Map<String, Object> map = new HashMap<>();
        map.put("seeker", seeker);

        File file = new File(realPath);
        String str = file.toString().substring(file.toString().lastIndexOf("."));
        System.out.println("file=" + file);
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(seeker.getJname()+str, "UTF-8"));
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
            byte[] b = new byte[fin.available()];
            fin.read(b);
            fin.close();
            ServletOutputStream out = response.getOutputStream();
            out.write(b);
            out.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}